<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="110px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="触发器名称" prop="triggerName">
						<el-input v-model="form.triggerName" placeholder="请输入触发器名称" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="数据模板" prop="dataTemplateId">
						<el-select v-model="form.dataTemplateId" placeholder="请选择数据模板" @change="handleChangeTemplate">
							<el-option v-for="item in templateOptions" :key="item.id" :value="item.id" :label="item.templateName"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="检测因子" prop="factorId">
						<el-select v-model="form.factorId" @change="handleChangeDivisor" placeholder="请选择检测因子">
							<el-option v-for="item in divisorList" :key="item.id" :label="item.cnName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="触发条件" prop="triggerConditions">
						<el-select v-model="form.triggerConditions" @change="handleChangeDivisor" placeholder="请选择触发条件">
							<el-option v-for="item in triggerConditionsList" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="触发值A" prop="triggerConditionsVala" v-if="!(form.triggerConditions === 2)">
						<el-input-number v-model="form.triggerConditionsVala" label="triggerConditionsVala" placeholder="请输入触发值A" :min="0" :max="999" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item
						label="触发值B"
						prop="triggerConditionsValb"
						v-if="form.triggerConditions === 2 || form.triggerConditions === 3 || form.triggerConditions === 4"
					>
						<el-input-number v-model="form.triggerConditionsValb" label="triggerConditionsValb" placeholder="请输入触发值B" :min="0" :max="999" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="报警方式">
						<el-checkbox v-model="form.smsAlarm" label="短信" :true-label="20" :false-label="10" />
						<el-checkbox v-model="form.telephoneAlarm" label="电话" :true-label="20" :false-label="10" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="触发器状态" prop="status">
						<el-switch v-model="form.status" :active-value="2" :inactive-value="1" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="BasicTriggerDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/platform/basicTrigger';
import { fetchListAll, fetchFactorDetailList } from '/@/api/platform/dataTemplate';
import { rule } from '/@/utils/validate';
import { triggerConditionsList } from './data';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const templateOptions: any = ref([]);
const divisorList: any = ref([]);
// 定义字典

// 提交表单数据
const form = reactive({
	id: '',
	triggerName: '',
	dataTemplateId: null,
	dataTemplateName: '',
	factorId: null,
	factorName: '',
	factorCode: '',
	triggerConditions: null,
	triggerConditionsVala: 0,
	triggerConditionsValb: 0,
	// alarmMethod: 2,
	status: 2,
	telephoneAlarm: 10,
	smsAlarm: 10,
});

// 定义校验规则
const dataRules = ref({
	triggerName: [{ required: true, message: '请输入', trigger: 'blur' }],
	dataTemplateId: [{ required: true, message: '请选择', trigger: 'change' }],
	factorId: [{ required: true, message: '请选择', trigger: 'change' }],
	triggerConditions: [{ required: true, message: '请选择', trigger: 'change' }],
	triggerConditionsVala: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				switch (form.triggerConditions as any) {
					case 4:
					case 3:
						if (value === form.triggerConditionsValb || value > form.triggerConditionsValb) {
							callback(new Error('触发值A不能大于触发值B'));
						} else {
							callback();
							unref(dataFormRef).clearValidate(['triggerConditionsValb']);
						}
						break;
					default:
						callback();
						break;
				}
			},
			trigger: 'blur',
		},
	],
	triggerConditionsValb: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			validator: (rule: any, value: any, callback: any) => {
				switch (form.triggerConditions as any) {
					case 4:
					case 3:
						if (value === form.triggerConditionsVala || value < form.triggerConditionsVala) {
							callback(new Error('触发值B不能小于触发值A'));
						} else {
							callback();
							unref(dataFormRef).clearValidate(['triggerConditionsVala']);
						}
						break;
					default:
						callback();
						break;
				}
			},
			trigger: 'blur',
		},
	],
});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';
	form.factorName = '';
	form.factorCode = '';
	form.dataTemplateName = '';
	form.telephoneAlarm = 10;
	form.smsAlarm = 10;

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	getTemplateOptions();

	// 获取basicTrigger信息
	if (id) {
		form.id = id;
		getbasicTriggerData(id);
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getbasicTriggerData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
			form.dataTemplateId && getDivisor(form.dataTemplateId as any);
		})
		.finally(() => {
			loading.value = false;
		});
};
const getTemplateOptions = () => {
	fetchListAll().then((res) => {
		templateOptions.value = res.data;
	});
};
const handleChangeTemplate = (e) => {
	const item = templateOptions.value.find((d) => d.id === e);
	form.factorName = '';
	form.factorCode = '';
	form.factorId = null;
	if (item) {
		form.dataTemplateName = item.templateName;
		getDivisor(e);
	}
};
const getDivisor = (dataTemplateId: string) => {
	fetchFactorDetailList({ id: dataTemplateId }).then((res) => {
		const l = res.data[0];
		l && (divisorList.value = res.data);
	});
};
const handleChangeDivisor = (e) => {
	const item = divisorList.value.find((d) => d.id === e);
	item && (form.factorName = item.cnName);
	item && (form.factorCode = item.code);
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
